/**
 * 此模块是用来进行用户登陆及登出的
 */
import { reqCodeUserInfo, reqRegisterUserInfo, reqUserLogin, reqUserToken, reqUserLogout, reqUserAddressInfo } from "@/api"

const state = {
    code: '',
    token: localStorage.getItem('token_key'),
    userInfo: {},
    addressList: [],
}

const mutations = {
    RECEIVE_CODE(state, code) {
        // console.log(code);
        state.code = code
    },
    RECEIVE_TOKEN(state, token) {
        state.token = token
    },
    RECEIVE_USERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    RESRT_USERINFO(state) {
        state.token = ''
        state.userInfo = {}
    },

    //拿到用户地址
    RECEIVE_ADDRESS(state, addressList) {
        state.addressList = addressList
    }

}

const actions = {
    //获取验证码
    async getCodeUserInfo({ commit }, phone) {
        const result = await reqCodeUserInfo(phone);
        // console.log(result);
        if (result.code = 200) {
            commit('RECEIVE_CODE', result.data)
            return result.data
        } else {
            return Promise.reject(new Error('failed'))
        }
    },
    //注册用户
    async getRegisterUserInfo({ commit }, user) {
        const result = await reqRegisterUserInfo(user);
        // console.log(result);
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('falied'))
        }
    },
    //用户登录
    async getLoginUserInfo({ commit }, user) {
        const result = await reqUserLogin(user)
        if (result.code === 200) {
            commit('RECEIVE_TOKEN', result.data.token)
            //保存到localStorage
            localStorage.setItem('token_key', result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },
    //根据token获取用户信息
    async getTokenUserInfo({ commit }) {
        const result = await reqUserToken()
        // console.log(result);
        if (result.code === 200) {
            commit('RECEIVE_USERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },
    // 用户登出
    async getUserLogout({ commit }) {
        const result = await reqUserLogout();
        if (result.code === 200) {
            localStorage.removeItem('token_key')
            commit('RESRT_USERINFO')
            return 'ok'
        } else {
            return Promise.reject(new Error('failed'))
        }
    },
    //获取用户地址
    async getUserAddressInfo({ commit }) {
        const result = await reqUserAddressInfo()
        // console.log('reqUserAddressInfo', result);
        if (result.code === 200) {
            commit('RECEIVE_ADDRESS', result.data)
            return 'ok'
        } else {
            alert('获取用户地址失败')
        }
    }

}

const getters = {
}

export default {
    namespaced: true, // 开启命名空间
    state,
    actions,
    mutations,
    getters
}